package com.google.code.chaotic.server;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;

import com.google.code.chaotic.ConversionUtil;
import com.google.code.chaotic.client.CommuterService;
import com.google.code.chaotic.client.NotLoggedInException;
import com.google.code.chaotic.dto.CommuterDto;
import com.google.code.chaotic.model.Commuter;
import com.google.gwt.user.client.rpc.InvocationException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

//

public class CommuterServiceImpl //
		extends RemoteServiceServlet implements CommuterService {

	// @PersistenceUnit(unitName = "backendWebLocal")
	// private EntityManagerFactory emf;

	// @PersistenceContext(unitName = "backendWebJTA", type = TRANSACTION)
	// private EntityManager em;

	@Override
	public String createCommuter(CommuterDto dto) throws NotLoggedInException {
		EntityManager em = EMF.getEntityManager(getThreadLocalRequest());
		// PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			return createCommuter(dto, em);

		} finally {
			em.close();
			// pm.close();
		}
	}

	public String createCommuter(CommuterDto dto, EntityManager em) {
		try {
			Commuter entity = ConversionUtil.dtoToEntity(dto);
			EntityTransaction tx = em.getTransaction();
			tx.begin();
			em.persist(entity);
			// pm.makePersistent(entity);
			tx.commit();
			dto.setId(entity.getId());
			return dto.getId();

		} catch (IllegalAccessException e) {
			e.printStackTrace();
			// TODO: All of such rethrowings must be dealt with!
			throw new InvocationException(e.getMessage(), e);

		} catch (InvocationTargetException e) {
			e.printStackTrace();
			throw new InvocationException(e.getMessage(), e);
		}
	}

	@Override
	public void deleteCommuter(String id) throws NotLoggedInException {
		// TODO Auto-generated method stub

	}

	@Override
	public List<CommuterDto> listCommuters() throws NotLoggedInException {
		// TODO Auto-generated method stub
		return null;
	}

}
